/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.openmrs.module.basicmodule.DSS.Interpreter.Function.Database;

import org.openmrs.module.basicmodule.DSS.Interpreter.DSSObservation;
import org.openmrs.module.basicmodule.DSS.Interpreter.Function.Function;
import org.openmrs.module.basicmodule.DSS.ast.IdTree;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openmrs.ConceptName;
import org.openmrs.Encounter;
import org.openmrs.Obs;
import org.openmrs.Patient;
import org.openmrs.api.context.Context;
import org.openmrs.module.basicmodule.DSS.Interpreter.InterpreterVisitor;
import org.openmrs.util.DatabaseUpdateException;
import org.openmrs.util.InputRequiredException;
import org.openmrs.util.OpenmrsUtil;

/**
 *
 * @author Stephen
 */
public class ReadLatestEncounterFunction extends Function{
  //  private static Properties props;
    
    @Override
    public Object execute(ArrayList args) {
           ArrayList<DSSObservation> retObs=new ArrayList();
        String conceptName = ((IdTree)args.get(1)).getSymbol().toString();
        try {
   //         start();
            retObs.add(readLatest(InterpreterVisitor.patientId,conceptName));
            System.out.println("Read latest \n"+retObs);
        } catch (Exception ex) {
            Logger.getLogger(ReadInitialEncounterFunction.class.getName()).log(Level.SEVERE, null, ex);        
        }
        finally{
    //        shutdown();
        }                
        return retObs;
    }
    
    public DSSObservation readLatest(int patientID, String concept)
    {
        Patient p = Context.getPatientService().getPatient(patientID);
        DSSObservation retDssObj=null;
        List<Encounter> allEncounters= Context.getEncounterService().getEncountersByPatient(p);
        for (Encounter encounter:allEncounters)
        {
            Set<Obs> allEncounterObs = encounter.getAllObs();
            for (Obs obs:allEncounterObs)
            {
                    int nameFlag=0;      
                    for ( ConceptName cn : obs.getConcept().getCompatibleNames(Locale.ENGLISH))
                        if (cn.toString().indexOf(concept.toUpperCase())!=-1)
                        {                            
                            nameFlag=1;                            
                        }
                    if (nameFlag==1)
                    {                                            
                            Date temp_date=encounter.getEncounterDatetime();
                            Object temp_value=obs.getValueNumeric();
                            String temp_name=obs.getConcept().getName().toString();
                            String temp_type=obs.getConcept().getDatatype().getName();                         
                            //SimpleDateFormat ft=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
                            SimpleDateFormat ft2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
                            Date logDate=new Date();
                            try{
                                logDate=ft2.parse(temp_date.toString());
                            }
                            catch(Exception e){
                                System.err.println(e.toString());
                            }                            
                            DSSObservation tempDssObj=new DSSObservation(logDate,temp_name,temp_value,temp_type);
                            retDssObj=tempDssObj;
                      }
            }
        }    
        return retDssObj;
    }
    
//    public void start() throws DatabaseUpdateException, InputRequiredException
//    {
//        System.out.flush();
//    String dir="C:\\Users\\Akhil\\AppData\\Roaming\\OpenMRS";
//     File propsFile = new File(dir, "openmrs-runtime.properties");
//    props = new Properties();
//    OpenmrsUtil.loadProperties(props, propsFile); 
//    
//    Context.startup("jdbc:mysql://localhost:3306/openmrs?autoReconnect=true", "user", "user123", props);
//  
//    Context.openSession();
//    Context.authenticate("admin", "Admin123");    
//    }
//  public void shutdown()
//  {
//     Context.closeSession();
//  }    
    
    private ArrayList getObs() {
        ArrayList myObs = new ArrayList();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
        Calendar cal = Calendar.getInstance();
        Date day;
        try {
            cal.setTime(dateFormat.parse("Sat Apr 13 10:45:08 PDT 2013"));
            day = cal.getTime();
            myObs.add(new DSSObservation(day, "weight", 130.3, "float"));
            
            cal.setTime(dateFormat.parse("Sat Apr 11 10:45:08 PDT 2013"));
            day = cal.getTime();
            myObs.add(new DSSObservation(day, "weight", 110.3, "float"));
            
            cal.setTime(dateFormat.parse("Sat Apr 14 10:45:08 PDT 2013"));
            day = cal.getTime();
            myObs.add(new DSSObservation(day, "weight", 140.3, "float"));
            
            cal.setTime(dateFormat.parse("Sat Apr 12 10:45:08 PDT 2013"));
            day = cal.getTime();
            myObs.add(new DSSObservation(day, "weight", 120.3, "float"));
        } catch (ParseException ex) {
            Logger.getLogger(ReadFunction.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return myObs;
    }
}
